package com.neuedu.controller;

import com.alibaba.fastjson.JSON;
import com.neuedu.domain.Member;
import com.neuedu.domain.OrderItem;
import com.neuedu.domain.Orders;
import com.neuedu.domain.Products;
import com.neuedu.service.WebOrdersService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Repository;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * @author ercai
 * @date 2019/8/5 - 16:36
 */
@Slf4j
@Controller
@RequestMapping("/orders")
public class WebOrdersController {

    @Autowired
    private WebOrdersService webOrdersService;

    //添加到购物车
    @RequestMapping("/addCart")
    public String toOrder(String id, HttpServletRequest request){

        //1.获取id

        //2.通过id查询数据库对应商品
        Products book = webOrdersService.findBook(Integer.parseInt(id));

        //3.把购买的商品放入Map
        //3.1先从session中获取购物车数据cart，
        Map<Products,Integer> cart = (Map<Products, Integer>) request.getSession().getAttribute("cart");

        //3.2 如果没有购物车数据 就创建一个Map
        if (cart == null) {
            cart = new HashMap<Products, Integer>();
            cart.put(book,1);
        }else {
            //3.3 判断map里面是否有当前想购买的商品
            if (cart.containsKey(book)) {      //map.containsKey()默认比较的是地址，需要重写equals方法，lombok已经为我们重写了
                cart.put(book,cart.get(book)+1);
            }else {
                cart.put(book,1);
            }
        }

        //4.打印购物车数据
        System.out.println(JSON.toJSONString(cart));

        //5.保存到session中
        request.getSession().setAttribute("cart",cart);

        return "web/cart";
    }

    /**
     * 更改购物车数量
     */
    @RequestMapping("/changeNum")
    public String changeNum(String id, String num,HttpServletRequest request){

        //1.获取参数

        //2.更新购物车数据
        //2.1通过id查找商品
        Products book = webOrdersService.findBook(Integer.parseInt(id));

        //2.2判断num不能大于库存
        if (Integer.parseInt(num)>book.getPnum()) {
            return "web/cart";
        }

        //2.3通过商品更新session
        Map<Products,Integer> cart = (Map<Products, Integer>) request.getSession().getAttribute("cart");

        //3.替换
        if (cart.containsKey(book)) {
            if ("0".equals(num)) {
                cart.remove(book);
            }else {
                cart.put(book,Integer.parseInt(num));
            }
        }

        //4.更新session
        request.getSession().setAttribute("cart",cart);

        //5.回到购物车页面
        return "web/cart";
    }

    /**
     * 结账功能
     */
    @RequestMapping("/settleAccount")
    public String settleAccount(HttpServletRequest request){

        //1.判断当前浏览器是否登录
        Member member = (Member) request.getSession().getAttribute("member");

        //2.登录了 跳到指定jsp
        if (member != null || true) {
            return "web/order";
        }

        //3.没有登录 跳到登录页面
        /*if (member == null) {
            return "web/login";
        }*/

        return null;
    }

    /**
     * 生成订单
     */
    @PostMapping("/createOrders")
    public String createOrders(Orders order,HttpServletRequest request){

        //1.获取session中的user对象
        Member member = (Member) request.getSession().getAttribute("member");
        if (member == null) {
            //跳转到登录页面
        }

        //2.封装order


        //3.1补全order数据
        order.setId(UUID.randomUUID().toString());
        order.setOrdertime(new Date());
        order.setPaystate(0);
        //order.setMember(member);
        double totalPrice = 0;

        //3.2封装订单详情orderItems 【一个订单有多个订单详情】
        List<OrderItem> orderItems = new ArrayList();
        Map<Products,Integer> cart = (Map<Products, Integer>) request.getSession().getAttribute("cart");
        for (Map.Entry<Products, Integer> entrySet : cart.entrySet()) {
            OrderItem orderItem = new OrderItem();
            orderItem.setBuynum(entrySet.getValue());
            orderItem.setProduct(entrySet.getKey());
            orderItem.setOrder(order);
            //计算订单总价格
            totalPrice += entrySet.getKey().getPrice()*entrySet.getValue();
            orderItems.add(orderItem);
        }
        //把总价格 产品详情封装到order中
        order.setMoney(totalPrice);
        order.setOrderItems(orderItems);
        //System.out.println(order);
//        for (OrderItem orderItem : orderItems) {
//            System.out.println(orderItem);
//        }
        //生成订单
        webOrdersService.createOrder(order);

        //订单成功，移除购物车cart
        request.getSession().removeAttribute("cart");

        return "web/createOrderSuccess";
    }

    /**
     * 通过用户id查找订单
     */
    @RequestMapping("/findOrderById")
    public String findOrderById(HttpServletRequest request,Model model){

        //1.获取session中member
        Member member = (Member) request.getSession().getAttribute("member");
        List<Orders> orders = webOrdersService.findOrderById(1);
        for (Orders order : orders) {
            System.out.println(order);
        }
        model.addAttribute("orders",orders);
        model.addAttribute("count",orders.size());
        return "web/orderlist";
    }

    /**
     * 查看订单详情 通过orderId查找订单详情
     */
    @RequestMapping("/findOrderByOrderId")
    public String findOrderByOrderId(String orderid,Model model){

        //1.先查出订单order
        Orders order = webOrdersService.findOrderByOrderId(orderid);
        model.addAttribute("order",order);
        return "web/orderInfo";
    }

    /**
     * 删除订单
     */
    @RequestMapping("/deleteOrderByOrderId")
    public String deleteOrderByOrderId(String orderid){


        return "";
    }
}
